package com.example.myapplication.utils;

import static com.example.myapplication.activity.PositionActivity.REQUEST_CODE_ACCESS_COARSE_LOCATION;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.Log;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//mainActivity中使用
//构建WifiUtils对象，然后利用对象调用方法getWifi
public class WifiUtils{

    public TextView show;

    public Context context;

    public Activity activity;

    private boolean flag;


    //创建wifiutils类
    public WifiUtils(Context context , Activity activity){
        this.context = context;
        this.activity = activity;
    }

    //获取wifi权限
    public void getLimit(WifiManager wm) {
        //动态申请权限
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.INTERNET)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.INTERNET}, 1);
        }


        //判断是否有wifi控制权限，没有的话进行权限获取
        if (!wm.isWifiEnabled()) {
            if (wm.getWifiState() != WifiManager.WIFI_STATE_ENABLING)
                wm.setWifiEnabled(true);
        }


        //获取位置权限判断与位置获取代码
        //app若要获取wifi信息，需要手机提供位置信息
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时
            //判断是否具有权限
            if (ContextCompat.checkSelfPermission(context,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要向用户解释为什么需要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    //showToast("自Android 6.0开始需要打开位置权限");
                }
                //请求权限
                ActivityCompat.requestPermissions(activity,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        1);
            }
        }
    }



    //获取扫描列表
    public List<ScanResult> getList(WifiManager wm){
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        List<ScanResult> resultList = wm.getScanResults();

        return resultList;
    }


    public WifiManager getManager(){
        WifiManager wm;
        wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wm;
    }


    //获取wifi信息

    @SuppressLint("MissingPermission")
    public StringBuilder getWifi() {
        //用于展示相关信息
        StringBuilder str = new StringBuilder();
        //定义wifimanager对象
        WifiManager wm = getManager();

        //开始扫描wifi
        //获取权限
        getLimit(wm);
        Map<String , Integer> levelMap = new HashMap<>();

//        BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context c, Intent intent) {
//                boolean success = intent.getBooleanExtra(
//                        WifiManager.EXTRA_RESULTS_UPDATED, false);
//                if (success) {
//
//                    scanSuccess();
//                } else {
//                    // scan failure handling
//                    scanFailure();
//                }
//            }
//        };
//
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
//        context.registerReceiver(wifiScanReceiver, intentFilter);

        for(int i =0;i<10;i++) {
            Map<Integer,String> WifiMap = new HashMap<>();
            //手动设置完成扫描
            List<ScanResult> resultList = null;
            boolean jud = wm.startScan();
            resultList = getList(wm);
            //用于找出强度排名靠前的wifi
            if(resultList != null)
            {
                for (ScanResult result : resultList) {
                    WifiMap.put(result.level, result.BSSID);
                    if(!levelMap.isEmpty()&&levelMap.containsKey(result.BSSID)) {
                        int level_now = levelMap.get(result.BSSID);
                        level_now += result.level;
                        levelMap.remove(result.BSSID);
                        levelMap.put(result.BSSID, level_now);
                    }
                }
                if(levelMap.isEmpty()){
                    List<Integer> sl = new ArrayList<>(WifiMap.keySet());
                    Collections.sort(sl);

                    for(int j =sl.size()-1;j>=sl.size()-11;j--)
                        levelMap.put(WifiMap.get(sl.get(j)),sl.get(j));
                }
            }
        }
        List<Integer> sm = new ArrayList<>();
        for(String name : levelMap.keySet()) {
            sm.add(levelMap.get(name) / 10);
            str.append(name).append(":").append(levelMap.get(name)/10).append(";").append("\n");
        }
        return str;
    }
    private void scanSuccess(){
        flag = true;
    }
    private void scanFailure(){
        flag = false;
    }
}


